const mongoose = require('mongoose')
const db = 'mongodb://localhost/douban'
const glob = require('glob')
const { resolve } = require('path')

mongoose.Promise = global.Promise


exports.initSchemas = () => {
    glob.sync(resolve(__dirname, './schema', '**/*.js')).forEach(require)
}

exports.connect = () => {
    return new Promise((resolve, reject) => {

        let MaxDisconnect = 0

        if (process.env.NODE_ENV !== 'production') {
            mongoose.set('debug', true)
        }

        mongoose.connect(db, {
            useMongoClient: true
        })

        mongoose.connection.on('disconnected', () => {
            MaxDisconnect++
            if (MaxDisconnect < 5) {
                mongoose.connect(db)
            } else {
                throw new Error('数据库挂了')
            }
        })

        mongoose.connection.on('error', err => {
            reject(err)
            console.log(err)
        })

        mongoose.connection.once('open', () => {
            resolve()
            console.log('mongodb connect successfully')
        })
    })
}